package com.manage.auth;

import java.io.PrintWriter;
import java.util.Date;
import java.util.List;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.apache.struts2.ServletActionContext;
import org.springframework.security.core.context.SecurityContextHolder;

import com.common.util.MD5;
import com.common.util.Page;
import com.common.util.Tools;
import com.model.auth.Role;
import com.model.auth.User;
import com.opensymphony.xwork2.ActionSupport;
import com.service.auth.IRoleService;
import com.service.auth.IUserRoleService;
import com.service.auth.IUserService;

public class UserAction extends ActionSupport {

	/**
	 * 
	 */
	private static final Logger log = Logger.getLogger(UserAction.class);
	private static final long serialVersionUID = 1L;
	@Resource
	private IUserService userService;
	
	@Resource
	private IRoleService roleService;
	
	@Resource
	private IUserRoleService userRoleService;
	
	private List<String> userRoles;
	
	private int pageNO;
	private int pageSize = 20;
	private List<User> userList;
	private User user;
	private Integer userCount;
	private Page page;
	private Integer id;
	private String ids;
	private String treeId;
	private List<Role> roleList;
	private String userName;
	private String result;
	
	private int[] userRoleCB;
	
	private String oldPwd;
	private String newPwd;
	
	public String list() {
		try {
			pageNO = pageNO < 0 ? 0 : pageNO;
			userCount = userService.getUserCount();
			userList = userService.getUserPageList(pageNO, pageSize);
			page = new Page(userCount,pageSize,pageNO);
		} catch (Exception e) {
			log.error("返回用户列表异常", e);
		}
		return "list";
	}

	// add
	public String add() {
		try{
			roleList = roleService.getAllRole();
		}catch(Exception e){
			log.error("查询部门列表异常", e);
		}
		return "add";
	}
	
	/**
	 * 验证账号是否已经存在
	 * @return
	 */
	public String checkAccount(){
		try{
			User user = userService.getUserByName(userName);
			int result = 0;
			if(user!=null){
				result = 0;
			}else{
				result =1;
			}
			HttpServletResponse response = ServletActionContext.getResponse();    
	        //设置字符集    
	        response.setCharacterEncoding("UTF-8");    
	        PrintWriter out = response.getWriter();    
	        //直接输入响应的内容    
	        out.println(result);
	        out.flush();    
	        out.close();
		}catch(Exception e){
			
			log.error("验证账号异常", e);
		}
		return null;
	}
	
	public String save() {
		try{
			if(user!=null){
				user.setCreateDate(new Date());
				if(StringUtils.isNotBlank(user.getPassword())){
					user.setLoginPwd(MD5.MD5Encode(user.getPassword()));
				}
				Integer userId =userService.insertUser(user);
				if(userRoleCB!=null && userId!=null){
					for(int i=0;i<userRoleCB.length;i++){
						userRoleService.insertUserRoles(userId, userRoleCB[i]);
					}
				}
			}
			result = "1";
		}catch(Exception e){
			log.error("保存用户异常", e);
			result = "0";
		}
		return "add";
	}

	
	/**
	 * 编辑 
	 * @return 
	 */
	public String edit() {
		try{
			if(id!=null){
				user = userService.getUserById(id);
			}
			roleList = roleService.getAllRole();
			userRoles = userRoleService.getRolesByUserId(id);
		}catch(Exception e){
			log.error("修改用户异常", e);
			result = "0";
		}

		return "edit";
	}
	
	/**
	 * 更新
	 * @return
	 */
	public String update(){
		try{
			if(user!=null){
				if(StringUtils.isNotBlank(user.getLoginPwd())){
					user.setLoginPwd(MD5.MD5Encode(user.getLoginPwd()));
				}
				userService.updateUser(user);
				Integer userId =user.getId();
				if(userId!=null){
					userRoleService.delUserRolesByUserId(userId);
					if(userRoleCB!=null){
						for(int i=0;i<userRoleCB.length;i++){
							userRoleService.insertUserRoles(userId, userRoleCB[i]);
						}
					}
				}
			}
			result = "1";
		}catch(Exception e){
			log.error("保存用户异常", e);
			result = "0";
		}
		return "edit";
	}
	
	
	public String delete(){
		try{
			if(id!=null && id!=1){
				userService.delUserById(id);
			}
			if(StringUtils.isNotBlank(ids)){
				String[] idList =ids.split(",");
				for(int i=0;i<idList.length;i++){
					if(!"1".equals(idList[i])){
						userService.delUserById(Integer.valueOf(idList[i]));
					}
				}
			}
			HttpServletResponse response = ServletActionContext.getResponse();    
	        //设置字符集    
	        response.setCharacterEncoding("UTF-8");    
	        PrintWriter out = response.getWriter();    
	        //直接输入响应的内容    
	        out.println(1);
	        out.flush();    
	        out.close();
		}catch(Exception e){
			log.error("删除模块列表异常", e);
			result="error";
		}
		return null;
	}
	
	/**
	 * 修改密码
	 * @return
	 */
	public String editPwd(){
		
		
		return "editPwd";
	}
	
	public String savePwd(){
		try{
			User correnUser  = getCurrentUser();
			User user = userService.getUserById(correnUser.getId());
			if(StringUtils.isNotBlank(oldPwd)){
				if(MD5.MD5Encode(oldPwd).equals(user.getPassword())){
					if(StringUtils.isNotBlank(newPwd)){
						userService.updateUserPwd(user.getId(), MD5.MD5Encode(newPwd));
						result="1";
					}else{
						result="3";
					}
				}else{
					//老密码错误
					result="2";
				}
			}else{
				//老密码错误
				result="2";
			}
		}catch(Exception e){
			log.error("保存修改密码", e);
		}
		return "editPwd";
	}
	
	public String getOldPwd() {
		return oldPwd;
	}

	public void setOldPwd(String oldPwd) {
		this.oldPwd = oldPwd;
	}

	public String getNewPwd() {
		return newPwd;
	}

	public void setNewPwd(String newPwd) {
		this.newPwd = newPwd;
	}

	public int[] getUserRoleCB() {
		return userRoleCB;
	}

	public void setUserRoleCB(int[] userRoleCB) {
		this.userRoleCB = userRoleCB;
	}

	public List<String> getUserRoles() {
		return userRoles;
	}

	public void setUserRoles(List<String> userRoles) {
		this.userRoles = userRoles;
	}

	public List<Role> getRoleList() {
		return roleList;
	}

	public void setRoleList(List<Role> roleList) {
		this.roleList = roleList;
	}

	public String getIds() {
		return ids;
	}

	public void setIds(String ids) {
		this.ids = ids;
	}

	public Integer getUserCount() {
		return userCount;
	}

	public void setUserCount(Integer userCount) {
		this.userCount = userCount;
	}

	public Page getPage() {
		return page;
	}

	public void setPage(Page page) {
		this.page = page;
	}
	

	public Integer getId() {
		return id;
	}

	public void setId(Integer id) {
		this.id = id;
	}

	public String getTreeId() {
		if (StringUtils.isNotBlank(treeId)) {
			Tools.getRequest().getSession().setAttribute("TREE_ID", treeId);
		} else {
			treeId = (String) Tools.getRequest().getSession().getAttribute(
					"TREE_ID");
		}
		return treeId;
	}
	
	public String getUserName() {
		return userName;
	}

	public String getResult() {
		return result;
	}

	public void setResult(String result) {
		this.result = result;
	}

	public void setUserName(String userName) {
		this.userName = userName;
	}

	public void setTreeId(String treeId) {
		this.treeId = treeId;
	}

	public User getUser() {
		return user;
	}

	public void setUser(User user) {
		this.user = user;
	}

	public List<User> getUserList() {
		return userList;
	}

	public void setUserList(List<User> userList) {
		this.userList = userList;
	}

	public int getPageNO() {
		return pageNO;
	}

	public void setPageNO(int pageNO) {
		this.pageNO = pageNO;
	}

	public int getPageSize() {
		return pageSize;
	}

	public void setPageSize(int pageSize) {
		this.pageSize = pageSize;
	}
	
	/**
	 * 获得当前用户
	 * @return
	 */
	private User getCurrentUser(){
		
		return (User) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
	}
}
